package com.zoshine.zzg.controller;

import com.zoshine.zzg.exception.AppException;
import com.zoshine.zzg.exception.ErrorMessage;
import com.zoshine.zzg.respons.ErrResponse;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 错误控制器
 *
 * @author 贾俊峰
 * @time 2017/6/19 17:08
 */
@Controller
public class ErrorController implements org.springframework.boot.autoconfigure.web.ErrorController {
    private static final String ERROR_PATH = "/error";

    /**
     * JSON请求错误
     */
    @RequestMapping(value = ERROR_PATH)
    @ResponseBody
    public Object error(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpStatus httpStatus = getStatus(request);
        response.setStatus(HttpStatus.OK.value());
        switch (httpStatus) {
            case NOT_FOUND:
                throw new AppException(ErrorMessage.INVALID_REQUEST_PATH);
            case INTERNAL_SERVER_ERROR:
                throw new AppException(ErrorMessage.SYSTEM_ERROR);
		default:
			break;
        }

        return new ErrResponse(-1, "未定义的错误");
    }

    /**
     * 页面请求错误
     */
    @RequestMapping(produces = "text/html", value = ERROR_PATH)
    public Object errorHtml(HttpServletRequest request,HttpServletResponse response, ModelMap map) {
        HttpStatus httpStatus = getStatus(request);
        response.setStatus(HttpStatus.OK.value());
        switch (httpStatus) {
            case NOT_FOUND:
                return new ModelAndView("error/404");
            case INTERNAL_SERVER_ERROR:
                return new ModelAndView("error/500");
            default:
                map.put("error.code", httpStatus.value());
        }
        return new ModelAndView("error/undefined");
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }


    /**
     * 获取错误编码
     */
    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
}
